package com.openatc.agent.service.impl;

import com.google.gson.*;
import com.openatc.agent.model.VipRoute;
import com.openatc.agent.model.VipRouteDevice;
import com.openatc.agent.model.VipRouteExecute;
import com.openatc.agent.service.VipRouteDao;
import com.openatc.agent.service.VipRouteDeviceDao;
import com.openatc.agent.utils.ApplicationContextProvider;
import com.openatc.agent.utils.HttpUtil;
import com.openatc.agent.utils.TokenUtil;
import com.openatc.core.util.GsonUtil;
import com.openatc.extend.common.aop.log.AbstractLogDataExtractor;
import com.openatc.extend.common.aop.model.WebOperationRecord;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @author ：panleilei
 * @description
 * @modified By：
 * @version:
 * @date ：Created in 2024/5/10 16:08
 */
public class VipRouteOperationRecordExtractor extends AbstractLogDataExtractor {
    private VipRouteDao vipRouteDao = ApplicationContextProvider.getBean(VipRouteDao.class);
    private int type;   // 调用方法时的类型  1、分组管控；2、特勤路线
    private int id; // 传入参数的id  0：新增；非0：修改或删除
    private String methodName; // 方法名称
    private static final Gson gson = GsonUtil.getInstance();

    public static final String GROUP_CONTROL= "group-control"; // 分组管理
    public static final String VIP_ROUTE="vip-route";// 特勤路线

    public static final String CREATE_GROUP_CONTROL = "updateVipRoute"; // 增加/修改分组管控
    public static final String DELETE_GROUP_CONTROL = "deleteVipRoute"; // 删除分组管控
    public static final String EXECUTE_VIP_ROUTES = "executeVipRoutes"; // 执行特勤路线

    public void setType(int type) {
        this.type = type;
    }
    public void setId(int id) {
        this.id = id;
    }
    static {
        // 删除分组管控/特勤路线
        addMethodNameType(DELETE_GROUP_CONTROL,DELETE_INFOTYPE);
        // 执行
        addMethodNameType(EXECUTE_VIP_ROUTES,DOWNLOAD_INFOTYPE);
    }

    @Override
    public void preExtract(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        this.methodName = method.getName();
        // 解析id和类型
        resolveIdAndType(point);
    }

    private void resolveIdAndType(ProceedingJoinPoint point) {
        if (CREATE_GROUP_CONTROL.equals(methodName)) {
            Object[] args = point.getArgs();
            VipRoute vipRoute = gson.fromJson(gson.toJson(args[0]), VipRoute.class);
            this.type = vipRoute.getType();
            this.id = vipRoute.getId();
            return;
        }
        if (EXECUTE_VIP_ROUTES.equals(methodName)) {
            Object[] args = point.getArgs();
            VipRouteExecute vipRouteExecute = (VipRouteExecute) args[0];
            this.id = vipRouteExecute.getViprouteid();
            VipRoute byId = vipRouteDao.findById(id);
            this.type = byId.getType();
            return;
        }
        if (DELETE_GROUP_CONTROL.equals(methodName)) {
            Object[] args = point.getArgs();
            this.id = (int) args[0];
            VipRoute byId = vipRouteDao.findById(id);
            this.type = byId.getType();
        }
    }

    @Override
    public Object extract(ProceedingJoinPoint point, Object ret) {
        WebOperationRecord record = new WebOperationRecord();

        record.setOperator(getOperatorName());
        record.setSource(HttpUtil.getIpAddress());
        record.setModel(getRecodeModel());
        record.setInfotype(getInfoType());
        record.setStatus(getStatus(ret));
        record.setRequestbody(getRequestBody(point.getArgs()));
        record.setResponsebody(getResponseBody(ret));
        record.setRequestsource(getRequestSocurce(methodName));

        return record;
    }


    /**
     * 获取方法的请求参数
     * @param args
     * @return
     */
    protected JsonElement getRequestBody(Object[] args) {
        Gson gson = new GsonBuilder().create();
        JsonArray requestBody = null;
        if (args != null && args.length != 0) {
            requestBody =  new JsonArray();
            for (Object obj : args) {
                if (obj instanceof JsonElement) {
                    requestBody.add((JsonElement) obj);
                    continue;
                }
                requestBody.add(gson.toJsonTree(obj));
            }
        }
        return requestBody;
    }



    /**
     * 获取请求来源
     * @return
     */
    private String getRecodeModel() {
        // 如果是分组管控/特勤路线，需要从参数中进行区分
        return type == 1 ? GROUP_CONTROL : VIP_ROUTE;
    }

    /**
     * 获取操作类型
     * @Param methodName
     * @return
     */
    protected String getInfoType() {
        if (CREATE_GROUP_CONTROL.equals(methodName)) {
            return id == 0 ? CREATE_INFOTYPE : MODIFY_INFOTYPE;
        }
        return super.getInfoType(methodName);
    }

    /**
     * 获取操作者
     * @return
     */
    private String getOperatorName() {
        return TokenUtil.getCurrentUserName();
    }


}
